package com.project.harmonyledger.config.filter;

import com.project.harmonyledger.mapper.UserMapper;
import com.project.harmonyledger.pojo.User;
import com.project.harmonyledger.utils.JwtUtil;
import com.project.harmonyledger.utils.UserDetailsImpl;
import io.jsonwebtoken.Claims;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.antlr.v4.runtime.misc.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.math.BigInteger;

@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
  @Autowired
  private UserMapper userMapper;

  @Override
  protected void doFilterInternal(HttpServletRequest request, @NotNull HttpServletResponse response,
      @NotNull FilterChain filterChain) throws ServletException, IOException {
    String token = request.getHeader("Authorization");

    if (!StringUtils.hasText(token) || !token.startsWith("Bearer ")) {
      filterChain.doFilter(request, response);
      return;
    }

    token = token.substring(7);

    String userid;
    try {
      Claims claims = JwtUtil.parseJWT(token);
      userid = claims.getSubject();
    } catch (Exception e) {
      throw new RuntimeException(e);
    }

    User user = userMapper.selectById(new BigInteger(userid));

    if (user == null) {
      throw new RuntimeException("用户名未登录");
    }

    UserDetailsImpl loginUser = new UserDetailsImpl(user);
    UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser, null,
        null);

    SecurityContextHolder.getContext().setAuthentication(authenticationToken);

    filterChain.doFilter(request, response);
  }
}
